package com.example.day_day_up.utils;

import com.example.day_day_up.config.AppConfig;
import com.example.day_day_up.exception.BusinessException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

public class FileUpload {

    // TODO
    // 返回存储好的material实例
    public static String upload(FileItem item) {
        try {
            // 上传的文件
            String fileName = item.getName();
            // 文件类型
            String fileExtension = "";
            int lastIndex = fileName.lastIndexOf(".");
            if (lastIndex != -1) {
                fileExtension = fileName.substring(lastIndex);
            }
            // 将文件写到指定目录
            String storeName = UUID.randomUUID() + fileExtension;
            item.write(new File(AppConfig.FILE_UPLOAD_RESOURCE + storeName));
            return storeName;
        } catch (FileUploadException e) {
            throw new BusinessException("文件上传失败");
        } catch (Exception e) {
            throw new BusinessException("文件上传未知错误");
        }
    }

}
